/*
 * @Author: Wilbur
 * @Date: 2019-01-08 14:59:16
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-03-05 16:51:49
 */
<template>
    <div class="container banner-add-wrap">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="formRule"
            label-width="110px"
            :disabled="false">
            <!-- 赞助商设置 -->
            <div class="form-unit">
                <div class="form-title">轮播图设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="title"
                    label="标题:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.title"
                        size="small"
                        class="task-input"/>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="pic_url"
                    label="轮播图图片:">

                    <el-upload
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfCustomerLogo(e)}"
                        accept="image/*"
                        class="upload-demo"
                        drag
                        action="https://jsonplaceholder.typicode.com/posts/">
                        <img
                            v-if="formData.pic_url"
                            :src="formData.pic_url"
                            class="avatar">
                        <i
                            class="el-icon-upload"
                            v-if="!formData.pic_url"/>
                        <div
                            class="el-upload__text"
                            v-if="!formData.pic_url">将文件拖到此处，或<em>点击上传</em></div>
                        <div
                            class="el-upload__tip"
                            slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                    <!-- <span style="display:inline-block;color:#999;margin-left:12px">*只能上传jpg/png文件</span> -->
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    label="跳转链接:">
                    <el-input
                        placeholder="非必填"
                        v-model="formData.link_url"
                        size="small"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*链接请包含http://</span>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="scope"
                    label="作用域:">
                    <el-checkbox-group v-model="formData.scope">
                        <el-checkbox
                            :label="1"
                            :value="1">首页登录前</el-checkbox>
                        <el-checkbox
                            :label="2"
                            :value="2">首页登录后</el-checkbox>
                        <el-checkbox
                            :label="4"
                            :value="4">广告主</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="showTime"
                    label="展示时间:">
                    <el-date-picker
                        v-model="formData.showTime"
                        type="datetimerange"
                        range-separator="至"
                        size="small"
                        class="task-input"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" />
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="sort"
                    label="排序:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.sort"
                        size="small"
                        prop="sort"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*数字越小排名越靠前</span>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    label="状态展示:">
                    <el-switch
                        v-model="formData.status"
                        active-color="#13ce66"
                        active-text="展示"
                        :active-value="1"
                        :inactive-value="0"
                        inactive-text="隐藏"/>
                </el-form-item>
            </div>

            <div class="form-unit">
                <div class="operate-baar">
                    <el-button
                        size="medium"
                        v-show="banner_id ? false : true"
                        @click="fnReset()">重置</el-button>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        var validateLinkUrl = (rule, val, callback) => {

            if(val.indexOf('http://') == -1){
                callback(new Error('错误'));
                return;
            }
            callback();
        };

        // 验证二位数组,且数组内元素不为空
        var validateArray = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };

        return {
            checkList: [1, 2],
            authResult: {},
            breadcrumbList: [
                {
                    title: "广告系统",
                },
                {
                    title: "轮播图列表",
                    name: 'bannerList',
                },
                {
                    title: '添加轮播图'
                }
            ],
            banner_id: '',
            provence: [],
            formData: {
                title: "",
                pic_url: '',
                link_url: '',
                scope: [],
                start_time: 0,
                end_time: 0,
                showTime: [this.fnInitTimeNow(), ''],
                status: 0
            },
            formRule: {
                link_url: [
                    { required: true, message: '请输入跳转', trigger: 'blur' },
                    { validator: validateLinkUrl, message: '请按要求填写链接', trigger: 'blur' }
                ],
                pic_url: [
                    { required: true, message: '轮播图图片不能为空', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字', trigger: 'blur' }
                ],
                scope: [
                    { type: 'array', required: true, message: '请选择作用域', trigger: 'change' }
                ],
                showTime: [
                    { required: true, message: '请填写展示时间', trigger: 'blur' },
                    { validator: validateArray, message: '请填写正确的时间', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请填写排序', trigger: 'blur' }
                ],
            },
            submitting: false,
            init: false,

            baseUrl: '',
            sessionTicket: localStorage.getItem('sessionTicket'),
            escape: escape,
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', this.breadcrumbList);

        this.banner_id = this.$route.query.banner_id ? this.$route.query.banner_id : '';

        if (!this.banner_id) {
            this.init = true;
        }else{
            this.fnInitBannerInfo();
        }
    },
    methods: {
        fnInitTimeNow() {
            var timestamp=new Date().getTime();

            return timestamp;
        },
        fnInitBannerInfo() {
            this.$post('/wei4/base%5Cbanner%5Cget', {
                id: this.banner_id
            }, resp => {
                if(resp.code == 1){
                    this.formData = {
                        ...resp.data,
                        showTime: [new Date(resp.data.start_time * 1000), new Date(resp.data.end_time * 1000)]
                    };
                    this.init = true;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnAreaLimitChange() {
            this.formData.limit_pids = [];
        },
        fnSubmit(){
            if(this.submitting){
                return ;
            }
            this.formData.intro = this.$refs.ueditor ? this.$refs.ueditor.getUEContent() : '';
            this.$refs.mainform.validate(valid => {
                if(valid){
                    this.submitting = true;

                    let data = {
                        title: this.formData.title,
                        pic_url: this.formData.pic_url,
                        link_url: this.formData.link_url,
                        scope : this.formData.scope.toString(),
                        start_time: Date.parse(this.formData.showTime[0])/1000,
                        end_time : Date.parse(this.formData.showTime[1])/1000,
                        sort: this.formData.sort,
                        status: this.formData.status,
                    };

                    if(this.banner_id){
                        data.id = this.banner_id;

                        this.$post('/wei4/base%5Cbanner%5Cedit', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '修改成功'
                                });
                                // this.$refs.mainform.resetFields();
                                this.$router.push({
                                    name: 'bannerList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }else{
                        this.$post('/wei4/base%5Cbanner%5Cadd', data, resp => {
                            if(resp.code == 1){
                                this.banner_id = resp.data.task_no;
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '操作成功'
                                });
                                this.$router.push({
                                    name: 'bannerList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }

                }
            });
        },
        /** 数组中删除某个元素 */
        fndeleteItem(list, index, bind) {
            list.splice(index, 1);
            this[bind] = list.length;
        },
        /** 上传组件回调 文件队列修改 */
        fnUploadChange(file, item) {
            item.preview_url = file.url;
        },
        fnBeforeUpload(file, item){
            item.status = 'uploading';
        },
        /** 上传组件回调 上传成功 */
        fnUploadSuccess(resp, file, item) {
            item.img_url = resp.url;
            item.status = 'success';
        },
        fnUploadError(item){
            item.preview_url = '';
            item.status = 'fail';
        },
        fnUpload(e, item) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            item.uploadTime = timeTmp;
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if(item.uploadTime != timeTmp){
                        return ;
                    }
                    if (resp.code == 1) {
                        // 调用组件成功回调,修改样式
                        e.onSuccess(resp.data, {
                            url: resp.data.url
                        }, this.fileList);
                    } else {
                        // 失败后调用组件error回调,删除对应元素
                        e.onError(resp.msg);
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                    }
                }
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnUploadImageOfCustomerLogo(e) {
            this.fnUploadImage(e, (resp) => {
                this.formData.pic_url = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnReset(){
            this.$refs.mainform.resetFields();
        }
    }
};
</script>

<style lang="less" scoped>
    .avatar{
        width: 100%;
        height: 100%;;
    }
    .margin-top{
        margin-top: 15px;
    }
    .banner-add-wrap {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 435px !important;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
</style>
<style lang="less">
</style>
